<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>待提交</title>
    <link rel="shortcut icon" type="image/x-icon" th:href="@{/static/img/favicon.ico}"/>

    <link rel="stylesheet" type="text/css"
          th:href="@{/plugins/bootstrap/css/bootstrap.min.css}">
    <link rel="stylesheet" type="text/css"
          th:href="@{/plugins/font-awesome/css/font-awesome.min.css}">
    <script th:src="@{/js/jquery.min.js}" crossorigin="anonymous"></script>
    <script th:src="@{/plugins/bootstrap/js/bootstrap.min.js}" crossorigin="anonymous"></script>
    <style>
        body {
            padding: 10px 5px;
        }

        #collectList {
            width: 100%;
        }

        #collectList > div {
            width: 30%;
            float: left;
            margin: 10px;
        }
        .collectInfo {
            border: 1px solid #bdbdbd;
            padding: 5px 10px;
            border-radius: 5px;
            background: #f5f5f5;
        }
        .collectInfo p {
            margin: 5px 0px;
            padding: 0px;
        }
        .form-group > label {
            margin-top: 20px;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>

<div id="collectList">
<!--    <div class="col-sm-6">-->
<!--        <div class="card">-->
<!--            <div class="card-body">-->
<!--                <h5 class="card-title">JS期末作业</h5>-->
<!--                <p class="card-text">2023-07-01（还有3天）</p>-->
<!--                <a href="#" class="btn btn-primary">去完成</a>-->
<!--            </div>-->
<!--        </div>-->
<!--    </div>-->
<!--    <div class="col-sm-6">-->
<!--        <div class="card">-->
<!--            <div class="card-body">-->
<!--                <h5 class="card-title">Java期末作业</h5>-->
<!--                <p class="card-text">2023-07-03（还有5天）</p>-->
<!--                <a href="#" class="btn btn-primary">去完成</a>-->
<!--            </div>-->
<!--        </div>-->
<!--    </div>-->

</div>


<div class="modal fade" id="submitCollectModal" data-backdrop="static" data-keyboard="false" tabindex="-1"
     aria-labelledby="staticBackdropLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="staticBackdropLabel">提交收集的文件</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="form-group collectInfo">
                    <p>
                        主题：<span id="collectTitle"></span>
                    </p>
                    <p>
                        描述：<span id="collectDesc"></span>
                    </p>
                </div>
                <div class="form-group">
                    <label for="chooseCollectFile">上传文件：</label>
                    <button type="button" class="btn btn-primary btn-sm" id="chooseCollectFileButton" >选择文件</button>&nbsp;<span id="uploadCollectMessage" th:default_text="'最大上传文件'+${maxFileSize}"></span>
                    <input type="file" class="form-control" hidden="true" id="chooseCollectFile" name="file" accept=".zip,.rar,.7z">
                </div>
                <input hidden="true" name="collectId" />
                <div class="form-group">
                    <label for="customFileName">重命名（可选）：</label>
                    <input type="text" class="form-control" id="customFileName" name="customFileName"
                           placeholder="将文件重命名（默认上传的文件名）...">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="submitCollect" >确认</button>
            </div>
        </div>
    </div>

</div>

<script type="module">
    import {POST, GET, POST_FORM} from "/js/request.js";
    import {formatDate} from '/js/formatDate.js'
    let currentUser = null;
    // 查出当前用户信息
    GET("/user/current").then(result=>{
        if (result.success) {
            currentUser = result.data;
        }else {
            alert("获取当前用户信息失败！")
        }
    })

    // 显示的列表数据
    let list = []
    function collectIdToCollectObj(collectId) {
        if (collectId == null) return null;
        for(let collect of list) {
            if (collect.id == collectId) return collect;
        }
        return null;
    }
    function getDaysRemainingDescribe(endTime) {
        if (endTime == null ) return '';
        endTime = new Date(endTime).getTime();
        let currentTime = Date.now();
        let dateCount = parseInt((endTime - currentTime)/1000/60/60/24);
        return dateCount == 0?`不到1天`:`还有${dateCount}天`;
    }
    // 获取collect 状态
    function getStatus(collect) {
        let isStarted = new Date(collect.startTime).getTime() < Date.now();
        let status = '去完成';
        if (! isStarted) {
            status = '未开始'
        }else if (collect.submitted){
            status = '重新提交';
        }
        return {
            status,
            isStarted
        }
    }
    function refreshUnCommitAndNotExpireList() {
        let listBox = $("#collectList");
        // 清空之前的内容
        listBox.html('')
        GET("/collect/getInProgressCollect").then(result=>{
            if (result.success) {
                console.log("要显示的列表数据：",result.data)
                list = result.data
                result.data.forEach(collect=>{
                    let status = getStatus(collect);
                    console.log("状态：",status)
                    listBox.append(`
                        <div class="col-sm-6">
                            <div class="card">
                                <div class="card-body">
                                    <h5 class="card-title">${collect.title}</h5>
                                    <p class="card-text">${formatDate(new Date(collect.endTime),'yyyy-MM-dd HH:mm')}（${getDaysRemainingDescribe(collect.endTime)}）</p>
                                    <button class="btn btn-primary submit toCompleteButton" data-toggle="modal" data-target="#submitCollectModal" collect_id="${collect.id}"  ${status.isStarted?'':'disabled'} >${status.status}</button>
                                </div>
                            </div>
                        </div>
                    `)
                })
            }else {
                alert("查询信息"+result.message)
            }
        })
    }
    refreshUnCommitAndNotExpireList();
    // 通知父容器，更新可“去完成”数量
    function noticeUpdateSubmittableCount() {
        window.parent.postMessage("UPDATE_SUBMITTABLE_COUNT_EVENT", '*');
    }
    // 用户点击提交
    $("#submitCollect").click(function () {
        let collectId = $("input[name='collectId']").val();
        let customFileName = $("input[name='customFileName']").val();
        POST("/collect/submitCollect",{
            collectId,
            customFileName
        }).then(result=>{
            if (result.success) {
                refreshUnCommitAndNotExpireList();
                noticeUpdateSubmittableCount();
                alert("提交收集内容成功！")
                $("#submitCollectModal").modal('hide')
            }else {
                alert("提交失败！"+result.message)
            }
        })
    })

    // 监听用户选择文件的事件
    $("#chooseCollectFile").change(function() {
        let uploadCollectMessage = $("#uploadCollectMessage");
        let collectId = $("input[name='collectId']").val();
        // 获取用户所选的文件对象
        if (this.files == null || this.files.length == 0) return;
        const file = this.files[0];
        uploadCollectMessage.html('<i class="fa fa-refresh" aria-hidden="true" /></i> 上传中...')
        POST_FORM("/collect/upload",{
            file,
            collectId
        }).then(result=>{
            if (result.success) {
                setTimeout(()=>uploadCollectMessage.text(file.name),500)
            }else {
                uploadCollectMessage.text('上传失败了！请重新上传')
                alert("上传失败！"+result.message)
            }
        }).catch(error=>{
            uploadCollectMessage.text('上传失败了，请重新上传')
        })
    })
    // 当点上传文件按钮的时候 - 选择文件
    $("#chooseCollectFileButton").click(function () {
        $("#chooseCollectFile").click()
    })
    function clearSubmitForm() {
        $("input[name='collectId']").val('');
        $("input[name='customFileName']").val('');
        $("#collectDesc").html('');
        $("#collectTitle").html('');
        let uploadCollectMessage = $("#uploadCollectMessage");
        uploadCollectMessage.html(uploadCollectMessage.attr('default_text'))
    }
    // 去完成/重新提交 点击按钮点击事件
    $("#collectList").on("click",".toCompleteButton",function () {
        // 清理表单内容
        clearSubmitForm()
        // 填充预信息
        $("#customFileName").val(currentUser.studentId+"_"+currentUser.nickname)

        // 将collect id 放到表单隐藏input中
        let collectId = $(this).attr("collect_id")
        let collectObj = collectIdToCollectObj(collectId)
        $("input[name='collectId']").val(collectId)
        $("#collectTitle").html(collectObj.title)
        $("#collectDesc").html(collectObj.describe)
    })

</script>

</body>
</html>